<template>
  <a-drawer
    v-model:visible="vdata.drawerVisible"
    :mask-closable="false"
    :title=" vdata.isAdd ? '新增设备' : '修改设备' "
    :body-style="{ paddingBottom: '80px' }"
    width="40%"
    class="drawer-width"
    @close="onClose"
  >
    <a-form v-if="vdata.drawerVisible" ref="infoFormModel" :model="vdata.saveObject" layout="horizontal" :rules="vdata.rules">
      <a-row v-if="vdata.isAdd" justify="space-between" type="flex">
        <a-col :span="11">
          <a-form-item label="设备号" name="deviceNo">
            <a-input v-model:value="vdata.saveObject.deviceNo" placeholder="请输入设备号" />
            <div v-if="vdata.checkMsg" :style="vdata.checkCode == 1 ? {'color' : 'green'} : {'color' : 'red'}">{{ vdata.checkMsg }}</div>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item>
            <a-button type="primary" @click="checkFunc">查询设备是否允许绑定</a-button>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row justify="space-between" type="flex">
        <a-col v-if="vdata.providerConfigList.length > 0 && vdata.checkCode == 2" :span="11">
          <a-form-item label="选择厂商" name="provider">
            <a-select v-model:value="vdata.saveObject.provider" :disabled="!vdata.isAdd" placeholder="请选择厂商">
              <a-select-option v-for="d in vdata.providerConfigList" :key="d.provider" v-model:value="d.provider">
                【{{ (allList.find(item => item.value == d.provider) as any).text || '其他' }}】{{ d.configDesc }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        
        <a-col :span="11">
          <a-form-item label="设备名称" name="deviceName">
            <a-input v-model:value="vdata.saveObject.deviceName" placeholder="请输入设备名称" />
          </a-form-item>
        </a-col>

        <a-col :span="11">
          <a-form-item label="选择门店" name="storeId">
            <a-select v-model:value="vdata.saveObject.storeId" placeholder="请选择门店" @change="onChangeStoreId">
              <a-select-option v-for="d in vdata.storeList" :key="d.storeId" v-model:value="d.storeId">
                {{ d.storeName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col :span="11">
          <a-form-item label="绑定类型" name="bindType">
            <a-radio-group v-model:value="vdata.saveObject.bindType">
              <a-radio :value="0">门店</a-radio>
              <a-radio :value="1">码牌</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row v-if="vdata.saveObject.bindType == 1" justify="space-between" type="flex">
        <a-col v-if="vdata.saveObject.qrcIdList && vdata.saveObject.qrcIdList.length > 0" :span="24">
          <a-form-item label="码牌ID">
            <a-textarea v-model:value="vdata.saveObject.qrcIdList" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item>
            <a-button type="primary" @click="showQrcSelectModel">{{ vdata.isAdd ? '选择绑定码牌' : '重新绑定码牌' }}</a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" style="margin-right:8px" @click="onClose"><close-outlined />取消</a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="handleOkFunc"><check-outlined />保存</a-button>
    </div>

    <!-- 选择码牌组件 -->
    <JeepayModelQrcList ref="jeepayModelQrcListRef" @selectFinishFunc="selectQrcFinishFunc" />
  </a-drawer>
</template>

<script lang="ts" setup>
import { API_URL_STORE_DEVICE, API_URL_MCH_STORE_LIST, req, $checkDevice } from '@/api/manage'
import { defineProps, reactive, ref, getCurrentInstance } from 'vue'
import provider from '../provider.json'

const allList = provider.all

const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
 
const props = defineProps({
  callbackFunc: { type: Function, default:null }
})

const infoFormModel = ref()
const jeepayModelQrcListRef = ref()

const  vdata = reactive({
  providerConfigList: [] as any, // 厂商列表
  storeList: [] as any, // 门店列表
  btnLoading: false,
  isAdd: true, // 新增 or 修改页面标志
  deviceType: 1, // 1-云喇叭 2-云打印 3-扫码POS
  saveObject: {} as any, // 数据对象
  recordId: null, // 更新对象ID
  drawerVisible: false, // 是否显示弹层/抽屉
  rules: {
    provider: [{ required: true, message: '请选择厂商', trigger: 'blur' }],
    storeId: [{ required: true, type: 'number', message: '请选择门店', trigger: 'blur' }],
    deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
    deviceNo: [{ required: true, message: '请输入设备号', trigger: 'blur' }],
    bindType: [{ required: true, message: '请选择绑定类型', trigger: 'blur' }],
    appId: [{
      required: false,
      trigger: 'blur'
    }, {
      validator: async (rule, value) => {
        if (vdata.deviceType == 3 && !value) {
            return Promise.reject('请选择应用')
        }
      }
    }] 
  }
}) as any


function show (record: any) { // 弹层打开事件

  vdata.isAdd = !record.deviceId
  vdata.deviceType = record.deviceType // 设备类型deviceType： 1-云喇叭, 2-云打印
  vdata.provider = record.provider

  vdata.saveObject = { 'state': 1, 'deviceType': record.deviceType }

  vdata.providerConfigList = []
  vdata.checkMsg = ''

  if (infoFormModel.value != undefined) {
    infoFormModel.value.resetFields()
  }

  req.list(API_URL_MCH_STORE_LIST, { 'pageSize': -1 }).then(res => { // 门店下拉选择列表
    vdata.storeList =  res.records
  })
  
  if (!vdata.isAdd) { // 修改信息 延迟展示弹层
    vdata.recordId = record.deviceId

    req.getById(API_URL_STORE_DEVICE, vdata.recordId).then((res: any) => {
      if(res){
        vdata.saveObject = res
        vdata.drawerVisible = true
      }
    })
  } else {
    vdata.drawerVisible = true
  }
}

function  handleOkFunc () { // 点击【确认】按钮事件
  infoFormModel.value.validate().then((valid: any) =>{
    addOrEdit()
  })
}

function addOrEdit() {
  vdata.btnLoading = true
  // 请求接口
  if (vdata.isAdd) {
    req.add(API_URL_STORE_DEVICE, vdata.saveObject).then((res: any) => {
      successFunc('保存成功')
    }).catch((err: any) => {
      vdata.btnLoading = false
    })
  } else {
    req.updateById(API_URL_STORE_DEVICE, vdata.recordId, vdata.saveObject).then((res: any) => {
      successFunc('修改成功')
    }).catch((err: any) => {
      vdata.btnLoading = false
    })
  }
}

function successFunc(e: string) { // 新增/更新成功
  vdata.btnLoading = false
  $infoBox.message.success(e)
  props.callbackFunc()
  vdata.drawerVisible = false
}

function checkFunc() {
  vdata.checkMsg = ''

  $checkDevice(vdata.saveObject.deviceNo, vdata.saveObject.deviceType).then(res => {
    vdata.checkCode = res.checkCode
    vdata.checkMsg = res.checkMsg

    if (vdata.checkCode == 2) {
      vdata.providerConfigList = res.deviceList
    }
  })
}

function showQrcSelectModel() {
  if (vdata.saveObject.storeId && vdata.saveObject.bindType == 1) {
    jeepayModelQrcListRef.value.show(vdata.saveObject.storeId, vdata.saveObject.qrcIdList)
  }
}

function onChangeStoreId() {
  vdata.saveObject.qrcIdList = []
}

function  selectQrcFinishFunc (e) { // 码牌选择完成事件

  if (!e || e.length <= 0) {
    return $infoBox.message.error('请开启要绑定的码牌！')
  }
  
  vdata.saveObject.qrcIdList = e
  jeepayModelQrcListRef.value.close()
}

function  onClose () { // 关闭抽屉
  vdata.drawerVisible = false
}
defineExpose({
  show
})
</script>
